package com.bawan.vims.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 将页面Table数据导出成Excel文件
 * 使用方式：
 * table需要定义 id，然后使用javascript获得table内容(document.all.table_id)
 * 调用/resources/js/commonUtil.js中的getTableData(document.all.table_id)获得Table内容字符串
 * 然后传给并调用TableExportExcelServlet
 * HTML:
 * <form method="post" action="" name="myForm" id="myForm">
 * 	<input type="hidden" name="tableContent" id="tableContent" value="">
 * 	<table id="tablelog" name="tablelog"></table>
 * 	<input type="button" value="导出" onclick="exportExcel();"/>
 * </form>
 * <iframe src="" width="0" height="0" id="iSaveFile" name="iSaveFile" scrolling="no"></iframe> 
 * 
 * Javascript:
 * function exportExcel() {
 * 	myForm.action = "<%path%>/tableExportExcelServlet/";
 *  myForm.tableContent.value = getTableData(document.all.tablelog);
 *  myForm.target = "iSaveFile";
 *  myForm.submit();
 * }
 * <p> Description	: TableExportToExcelServlet.java </p>
 * <p> Copyright	: Copyright (c) 2015 by FITT</p>
 * <p> Author 		: ZCC </p>
 * <p> Create		: 2015年4月10日 上午10:06:46 </p> 
 * <p> version 		: 1.0 </p>
 */
public class TableExportExcelServlet extends HttpServlet {
	private static final long serialVersionUID = 1314132645116954220L;
	private Logger logger = LoggerFactory.getLogger(TableExportExcelServlet.class);
	private static final String CONTENT_TYPE = "application/vnd.ms-excel;charset=GB2312";

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			request.setCharacterEncoding("GB2312");
			response.setContentType(CONTENT_TYPE);
			String title = request.getParameter("title");
			if ((title == null) || (title.equals("")))
				title = "result";
			String postFix = request.getParameter("postFix");
			logger.debug("postFix = " + postFix);
			if ((postFix == null) || (postFix.equals(""))) {
				postFix = "csv";
			}
			String content = request.getParameter("tableContent");
			logger.debug("TableExportExcelServlet.doPost() tableContent=" + content);
			if ("csv".equalsIgnoreCase(postFix)) {
				String attachFilename = title + ".xls";
				attachFilename = new String(attachFilename.getBytes("GB2312"), "8859_1");
				response.setCharacterEncoding("gb2312");
				response.setContentType("application/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename=" + attachFilename);
				OutputStream out = response.getOutputStream();
				WritableWorkbook workbook = Workbook.createWorkbook(out);

				WritableSheet sheet = workbook.createSheet(title, 0);

				if (content != null && content.contains("_[$]_")) {
					String[] lines = content.split("_[$]_");
					if (lines != null) {
						for (int i = 0; i < lines.length; i++) {
							String linesStr = lines[i];
							String[] lineArray = linesStr.split(",");
							for (int j = 0; j < lineArray.length; j++) {
								String line = lineArray[j];
								if (line == null)
									line = "";
								else {
									line = line.trim();
								}
								logger.debug(lineArray[j].trim());
								Label dataLabel = new Label(j, i, line);
								sheet.addCell(dataLabel);
							}
						}
					}
				}

				workbook.write();
				workbook.close();
			} else {
				response.setHeader("Content-disposition", "attachment;filename=" + title + "." + postFix);
				PrintWriter out = response.getWriter();
				String[] lines = content.split("_[$]_");
				if (lines != null) {
					for (int i = 0; i < lines.length; i++) {
						out.println(lines[i]);
					}
				}

				out.close();
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}
